from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from comments.forms import CommentForm
from comments.models import Comments
from blog.models import Blog

# Create your views here.


class CommentView(View):

    def get(self, request, blog_pk):
        blog = get_object_or_404(Blog, pk=blog_pk)
        return render(blog)

    def post(self, request, blog_pk):
        blog = get_object_or_404(Blog, pk=blog_pk)
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.name = request.user.nickname
            comment.email = request.user.email
            comment.blog = blog
            comment.save()
            return redirect(blog)
        else:
            comment_list = blog.comments_set.all()
            context = {
                'blog': blog,
                'form': form,
                'comment_list': comment_list
            }
            return render(request, 'blog/detail.html', context=context)
